package com.sjgtw.cloud.web.floodCtrlRecord.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.floodCtrlRecord.domain.FloodCtrlRecord;
import com.sjgtw.cloud.web.floodCtrlRecord.mapper.FloodCtrlRecordMapper;
import com.sjgtw.cloud.web.floodCtrlRecord.service.IFloodCtrlRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 防洪抢修记录Service业务层处理
 * 
 * @author lvyoufang
 * @date 2024-03-14
 */
@Service
public class FloodCtrlRecordServiceImpl implements IFloodCtrlRecordService 
{
    @Autowired
    private FloodCtrlRecordMapper floodCtrlRecordMapper;

    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询防洪抢修记录
     * 
     * @param id 防洪抢修记录主键
     * @return 防洪抢修记录
     */
    @Override
    public FloodCtrlRecord selectFloodCtrlRecordById(Long id)
    {
        return floodCtrlRecordMapper.selectFloodCtrlRecordById(id);
    }

    /**
     * 查询防洪抢修记录列表
     * 
     * @param floodCtrlRecord 防洪抢修记录
     * @return 防洪抢修记录
     */
    @Override
    public List<FloodCtrlRecord> selectFloodCtrlRecordList(FloodCtrlRecord floodCtrlRecord)
    {
        return floodCtrlRecordMapper.selectFloodCtrlRecordList(floodCtrlRecord);
    }

    /**
     * 新增防洪抢修记录
     * 
     * @param floodCtrlRecord 防洪抢修记录
     * @return 结果
     */
    @Override
    public int insertFloodCtrlRecord(FloodCtrlRecord floodCtrlRecord)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        Long userId = user.getUserid();
        String username = user.getUsername();

        floodCtrlRecord.setCreateUserId(userId);
        floodCtrlRecord.setCreateBy(username);
        floodCtrlRecord.setCreateTime(DateUtils.getNowDate());
        return floodCtrlRecordMapper.insertFloodCtrlRecord(floodCtrlRecord);
    }

    /**
     * 修改防洪抢修记录
     * 
     * @param floodCtrlRecord 防洪抢修记录
     * @return 结果
     */
    @Override
    public int updateFloodCtrlRecord(FloodCtrlRecord floodCtrlRecord)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        Long userId = user.getUserid();
        String username = user.getUsername();

        floodCtrlRecord.setUpdateBy(username);
        floodCtrlRecord.setUpdateTime(DateUtils.getNowDate());
        return floodCtrlRecordMapper.updateFloodCtrlRecord(floodCtrlRecord);
    }

    /**
     * 批量删除防洪抢修记录
     * 
     * @param ids 需要删除的防洪抢修记录主键
     * @return 结果
     */
    @Override
    public int deleteFloodCtrlRecordByIds(String[] ids)
    {
        return floodCtrlRecordMapper.deleteFloodCtrlRecordByIds(ids);
    }

    /**
     * 删除防洪抢修记录信息
     * 
     * @param id 防洪抢修记录主键
     * @return 结果
     */
    @Override
    public int deleteFloodCtrlRecordById(Long id)
    {
        return floodCtrlRecordMapper.deleteFloodCtrlRecordById(id);
    }

    @Override
    public List<String> check(List<FloodCtrlRecord> entities) {
        List<String> errors = new ArrayList<>();
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        List<String> deptNames = extractAndDeduplicateNames(entities);
        AjaxResult result = systemServerService.getDeptByNames(StringUtils.join(deptNames, ","));
        Map<String, Long> deptMap = new HashMap<>();
        if (result != null) {
            Object object = result.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        deptMap.put(json.getString("deptName"), json.getLong("deptId"));
                    }
                }
            }
        }

        for (FloodCtrlRecord entity : entities) {
            if (StringUtils.isEmpty(entity.getSectionName())) {
                errors.add("序号为" + entity.getNum() + "行数据区段不能为空");
            } else if (deptMap.containsKey(entity.getSectionName())) {
                entity.setSection(deptMap.get(entity.getSectionName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据区段不存在");
            }

            if (StringUtils.isEmpty(entity.getWorkAreaName())) {
                errors.add("序号为" + entity.getNum() + "行数据工区不能为空");
            } else if (deptMap.containsKey(entity.getWorkAreaName())) {
                entity.setWorkArea(deptMap.get(entity.getWorkAreaName()));
            } else {
                errors.add("序号为" + entity.getNum() + "行数据工区不存在");
            }
            if (user != null) {
                entity.setCreateUserId(user.getUserid());
                entity.setCreateBy(user.getUsername());
            }
            entity.setCreateTime(DateUtils.getNowDate());
        }
        return errors;
    }

    @Override
    public void batchSave(List<FloodCtrlRecord> entities) {
        if (entities != null && entities.size() > 0) {
            if (entities.size() >= 200) {
                int index = 0;
                while (index <= entities.size()) {
                    int last = Math.min(index + 200, entities.size());
                    List<FloodCtrlRecord> temp = entities.subList(index, last );
                    if (temp != null && temp.size() > 0) {
                        floodCtrlRecordMapper.batchSave(temp);
                    }
                    index += 200;
                }
            } else {
                floodCtrlRecordMapper.batchSave(entities);
            }
        }
    }

    private static List<String> extractAndDeduplicateNames(List<FloodCtrlRecord> entities) {
        Set<String> uniqueNamesSet = new HashSet<>();

        for (FloodCtrlRecord entity : entities) {
            uniqueNamesSet.add(entity.getSectionName());
            uniqueNamesSet.add(entity.getWorkAreaName());
        }

        return new ArrayList<>(uniqueNamesSet);
    }
}
